<template>
  <view class="container">
    <view class="header">
      <!-- 返回按钮 -->
      <view @click="goHome">
        <u-icon name="arrow-left" size="30" color="#888" />
      </view>
      <text class="title">消息中心</text>
      <!-- 清除未读消息按钮 -->
      <view @click="onClearClick" class="footer-item">
        <u-icon name="trash" size="30" color="#888" />
      </view>
    </view>
    <!-- 清除未读消息的确认弹窗 -->
    <view v-if="showModal">
      <uni-modal
        title="提示"
        content="是否清除所有未读消息"
        @confirm="clearUnreadNotifications"
        @cancel="cancelClear"
      />
    </view>
  </view>
</template>

<script>
// import UIcon from 'node_modules/uview-ui/components/u-icon/u-icon.vue'; // 手动引入

export default {
  components: {
    // UIcon,
  },

  data() {
    return {
      checkedValues: [], // 绑定复选框的选中值
      showModal: false,   // 控制清除确认弹窗的显示与否
      notifications: [],  // 存储从后端获取的通知
    };
  },
  mounted() {
    // 页面加载时获取通知数据
    this.fetchNotifications();
  },
  methods: {
    goHome() {
      uni.switchTab({
        url: '/pages/index/index'
      });
    },
    cancelClear() {
      // 取消清除操作
      this.showModal = false;
    },

    // 点击垃圾桶图标，弹出确认清除未读消息弹窗
    onClearClick() {
      // 过滤出未读的通知
      const unreadNotifications = this.notifications.filter(item => !item.read);
      if (unreadNotifications.length > 0) {
        this.showModal = true;  // 显示清除未读消息的弹窗
      } else {
        this.$u.toast('没有未读消息');
      }
    },

    // 清除未读消息
    clearUnreadNotifications() {
      // 清除未读通知，更新通知列表
      this.notifications = this.notifications.filter(item => item.read);
      this.showModal = false;  // 关闭弹窗
      this.$u.toast('未读消息已清除');
    },

    // 获取通知数据
    fetchNotifications() {
      uni.request({
        url: 'https://your-api-endpoint.com/notifications', // 你自己的后端 API 地址
        method: 'GET',
        success: (response) => {
          // 假设返回的通知数据在 response.data 中
          this.notifications = response.data;
        },
        fail: (error) => {
          console.error('获取通知数据失败：', error);
          this.$u.toast('加载通知失败');
        }
      });
    },
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.footer-item {
  padding: 10px;
}
</style>